<?php

/**
 * @Author: Wang Chunsheng 2192138785@qq.com
 * @Date:   2020-03-10 20:37:35
 * @Last Modified by:   Wang Chunsheng 2192138785@qq.com
 * @Last Modified time: 2020-03-29 21:18:29
 */


namespace common\addons\diandi_shop\services;

use common\addons\diandi_shop\models\DdCategory;
use Yii;
use common\addons\diandi_shop\models\DdGoods;
use common\addons\diandi_shop\models\DdGoodsParam;
use common\addons\diandi_shop\models\DdGoodsSpec;
use common\addons\diandi_shop\models\DdGoodsSpecRel;
use common\addons\diandi_shop\models\DdSpec;
use common\addons\diandi_shop\models\DdSpecValue;
use common\addons\diandi_shop\models\GoodsLabel;
use common\components\MyStringHelp;
use common\helpers\ArrayHelper;
use common\helpers\ErrorsHelper;
use common\helpers\ImageHelper;
use common\helpers\LevelTplHelper;
use common\services\BaseService;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;

class GoodsService extends BaseService
{
    const INACTIVE = 0;
    const ACTIVE = 10;
    /**
     * 获取商品列表
     * 默认分页参数为page
     * @param int|null post
     * @return string
     * @throws NotFoundHttpException
     */
    public static function getList($category_pid = 0, $category_id = 0, $keywords = '', $pageSize = 10, $user_id = '')
    {
        $page = Yii::$app->request->get('page');
        $keys = 'goodsinfo_' . $category_pid . $category_id . $page;
        // if (Yii::$app->cache->get($keys)) { //如果有缓存数据则返回缓存数据，没有则从数据库取病存入缓存中

        //     return Yii::$app->cache->get($keys);
        // } else {
        $where = []; //初始化条件数组
        if (!empty($category_pid)) {
            $where['category_pid'] = $category_pid;
        }
        if (!empty($category_id)) {
            $where['category_id'] = $category_id;
        }
        if (!empty($keywords)) {
            $where = array_merge($where, ['like', 'goods_name', $keywords]);
        }
        // 创建一个 DB 查询来获得所有
        $query = DdGoods::find()->where($where);
        // 得到文章的总数（但是还没有从数据库取数据）
        $count = $query->count();
        // 'pageSize' => 10,'pageSizeParam'=>false.............]);中的参数
        // 'totalCount' 为数据总数
        // 'pageSize' 为每页显示数
        // 'pageSizeParam'=>false, 可将分页路径中per-page参数隐藏去掉
        // 'pageParam' => 'p', 可更改分页url中分页参数name名称
        // 'route' => false, 当分页在于首页时隐藏掉路由，将/site/index?p=1变为/?p=1
        // 'validatePage' => false, 取消分页验证,当手动输入page=20时不再跳到page=1
        // 使用总数来创建一个分页对象
        $pagination = new Pagination([
            'totalCount' => $count,
            'pageSize' => $pageSize
        ]);
        $list = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->asArray()
            ->all();
        // 获取当前用户购物车数量
        $cartlist = CartService::list($user_id);
        $cart = ArrayHelper::arrayKey($cartlist['goods'], 'goods_id');
        // 获取标签
        $labels = GoodsLabel::find()->all();
        $label = ArrayHelper::arrayKey($labels, 'label');

        foreach ($list as &$item) {
            $item['thumb'] = ImageHelper::tomedia($item['thumb']);
            $images = unserialize($item['images']);
            $item['images'] = ImageHelper::tomedia($images);
            $item['number'] = $cart[$item['goods_id']]['number'] ? $cart[$item['goods_id']]['number'] : 0;
            if (!empty($item['label'])) {
                $item['label_color'] = $label[$item['label']]['color'];
            }
        }
        Yii::$app->cache->set($keys, $list, 3600);

        return $list;
        // }
    }


    public static function getDetail($goods_id)
    {

        $goods = DdGoods::find()
            ->with(['category', 'specRel', 'goodsSpec'])
            ->where(['goods_id' => $goods_id])
            ->asArray()
            ->one();
        $specs = [];
        if (!empty($goods['specRel'])) {
            $spec_value_ids = array_column($goods['specRel'], 'spec_value_id');
            $spec_ids = array_column($goods['specRel'], 'spec_id');

            $spec = DdSpec::find()->where(['spec_id' => $spec_ids])->indexBy('spec_id')->all();
            $specVal = DdSpecValue::find()->where(['spec_value_id' => $spec_value_ids])
                ->indexBy('spec_value_id')->all();
            foreach ($goods['specRel'] as &$item) {
                $item['thumb'] = ImageHelper::tomedia($item['thumb']);
                $item['spec_title'] =  $spec[$item['spec_id']]['spec_name'];
                $item['specVal_title'] =  $specVal[$item['spec_value_id']]['spec_value'];
                $specs['listId'][$item['spec_id']][] = $item['spec_value_id'];
                $specs['list'][$item['spec_title']][] = $item['specVal_title'];
            }

            $specSets  = ArrayHelper::arrayKey($goods['goodsSpec'], 'spec_sku_id');
            if (!empty($specSets)) {
                foreach ($specSets as $key => $item) {
                    $k = explode('_', $key);
                    $ks = [];
                    foreach ($k as $val) {
                        $ks[] = $specVal[$val]['spec_value'];
                    }
                    $newKey = implode('_', $ks);
                    $specs['specSet'][$newKey] = $item;
                }
            }
        }
        $goods['specs'] = $specs;

        // 处理图片
        $goods['thumb'] = ImageHelper::tomedia($goods['thumb']);
        $goods['images'] = ImageHelper::tomedia(unserialize($goods['images']));
        // 增加一次浏览
        DdGoods::updateAllCounters(['browse' => 1], ['goods_id' => $goods_id]);
        return $goods;
    }
}
